package com.bjkcst.baselib.protocolparse;


import android.util.Log;

import com.bjkcst.baselib.protocolparse.annotation.BeanFieldBitAnnotation;
import com.bjkcst.baselib.protocolparse.annotation.BeanFieldEndianAnnotation;
import com.bjkcst.baselib.protocolparse.annotation.BeanFieldListAnnotation;
import com.bjkcst.baselib.protocolparse.bean.ByteList;
import com.bjkcst.baselib.protocolparse.bean.DefByte2Int;
import com.bjkcst.baselib.protocolparse.bean.DefTByte2Int;
import com.bjkcst.baselib.protocolparse.bean.DefaultBit;
import com.bjkcst.baselib.protocolparse.endian.Endian;
import com.bjkcst.baselib.protocolparse.endian.EndianUtils;
import com.bjkcst.baselib.protocolparse.example.ReceiveBitExamples;

import org.checkerframework.checker.units.qual.A;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;

/**
 * 接收解析 bit 数据可以参考示例 {@link ReceiveBitExamples}
 */
public class ConvertorUtil {

    private static final String packageBitStr = "com.bjkcst.baselib.protocolparse.bean.Bit";
    private static final String packageByte2IntStr = "com.bjkcst.baselib.protocolparse.bean.Byte2Int";
    private static final String packageTByte2IntStr = "com.bjkcst.baselib.protocolparse.bean.TByte2Int";


    /**
     * 保存解析完的字段，读和写实体类不能使用同一个
     */
    private static Map<String, ArrayList<Field>> parseFieldValues = new HashMap<>();

    /**
     * 字节数组向对象进行转化
     *
     * @param bytes 输入的byte数组
     * @param clazz 需要创建的对象类
     * @param <T>   泛型
     * @return 转换后的对象
     */
    public static <T> T byteToObject(byte[] bytes, Class<T> clazz) {
        T instance = null;
        try {
            instance = clazz.newInstance();
        } catch (Exception e) {
            throw new RuntimeException("实例化类失败", e);
        }
        ArrayList<Field> fieldsValues = parseFieldValues.get(clazz.getSimpleName());
        if (fieldsValues == null || fieldsValues.size() == 0) {
            fieldsValues = new ArrayList<>();
            getFields(clazz, fieldsValues);
            parseFieldValues.put(clazz.getSimpleName(), fieldsValues);
        }
        ByteBuf buffer = Unpooled.buffer().writeBytes(bytes);
        for (Field field : fieldsValues) {
            fillData(field, instance, buffer);
        }

        return instance;
    }

    /**
     * 获取对象的变量
     *
     * @param clazz 类
     * @param list  变量存储列表
     * @return 变量列表
     */
    private static List<Field> getFields(Class clazz, List list) {
        Field[] fields = clazz.getDeclaredFields();
        List<Field> orderedField = OrderedFieldUtils.getOrderedField(fields);
        list.addAll(orderedField);
        return list;
    }


    private static List<Field> getBitFields(Class clazz, List list) {
        Field[] fields = clazz.getDeclaredFields();
        List<Field> orderedField = OrderedFieldUtils.getBitField(fields);
        list.addAll(orderedField);
        return list;
    }

    /**
     * 通过类型赋值
     *
     * @param field    属性
     * @param instance 对象
     * @param buffer   数据
     */
    private static void fillData(Field field, Object instance, ByteBuf buffer) {

        field.setAccessible(true);

        String typeName = field.getType().getName();
        Class<?> superclass = field.getType().getSuperclass();
        if (superclass != null) {
            String superName = superclass.getName();
            if (superName.contains(packageBitStr)) {
                typeName = packageBitStr;
            } else if (superName.contains(packageByte2IntStr)) {
                typeName = packageByte2IntStr;
            } else if (superName.contains(packageTByte2IntStr)) {
                typeName = packageTByte2IntStr;
            }
        }
        try {
            switch (typeName) {
                case "java.util.ArrayList":
                    ArrayList<Integer> valueList = new ArrayList<>();
                    BeanFieldListAnnotation annotationList = field.getAnnotation(BeanFieldListAnnotation.class);
                    int offset = annotationList.offset();
                    int totalLength = annotationList.totalLength();
                    ByteBuf byteBufList = buffer.readBytes(totalLength);
                    byte[] listByteValue = byteBufList.array();
                    for (int i = 0; i < totalLength; i = i + offset) {
                        byte[] readArray = Arrays.copyOfRange(listByteValue, i, i + offset);
                        int valueT = EndianUtils.be2Int2Byte(readArray);
                        valueList.add(valueT);
                    }
                    field.set(instance, valueList);
                    break;
                case "com.bjkcst.baselib.protocolparse.bean.Bit":
                    byte byteValue = buffer.readByte();
                    int[] bitAar = DataProcessUtils.getBitValue(byteValue);
                    Object superClass = field.getType().newInstance();
                    ArrayList<Field> fieldList = parseFieldValues.get(superClass.getClass().getSimpleName());
                    if (fieldList == null || fieldList.size() == 0) {
                        fieldList = new ArrayList<>();
                        assert superclass != null;
                        getBitFields(Objects.requireNonNull(superClass.getClass()), fieldList);
                        parseFieldValues.put(superClass.getClass().getSimpleName(), fieldList);
                    }
                    for (Field declaredField : fieldList) {
                        BeanFieldBitAnnotation annotation = declaredField.getAnnotation(BeanFieldBitAnnotation.class);
                        String value = annotation.value();
                        int order = annotation.order();
                        Field field1 = superClass.getClass().getField(value);
                        field1.set(superClass, bitAar[order - 1]);
                    }
                    field.set(instance, superClass);
                    break;
                case "com.bjkcst.baselib.protocolparse.bean.Byte2Int":
                    byte bi = buffer.readByte();
                    int value = bi & 0xFF;
                    Object superClassi = field.getType().newInstance();
                    Field field1 = superClassi.getClass().getField("Int");
                    field1.set(superClassi, value);
                    field.set(instance, superClassi);
                    break;
                case "com.bjkcst.baselib.protocolparse.bean.TByte2Int":
                    ByteBuf byteBuf = buffer.readBytes(2);
                    byte[] array = byteBuf.array();
                    //字节序处理  字段注解字节序优先级高于默认字节序
                    int valueT;
                    Endian defaultEndian = ProtocolConfig.getDefaultEndian();
                    if (defaultEndian == Endian.LITTLE_ENDIAN) {
                        valueT = EndianUtils.le2Int2Byte(array);
                    } else {
                        valueT = EndianUtils.be2Int2Byte(array);
                    }
                    BeanFieldEndianAnnotation endianAnnotation = field.getAnnotation(BeanFieldEndianAnnotation.class);
                    if (endianAnnotation != null) {
                        Endian endian = endianAnnotation.value();
                        if (endian == Endian.LITTLE_ENDIAN) {
                            valueT = EndianUtils.le2Int2Byte(array);
                        } else {
                            valueT = EndianUtils.be2Int2Byte(array);
                        }
                    }

                    Object superClasst = field.getType().newInstance();
                    Field fieldt = superClasst.getClass().getField("Int");
                    fieldt.set(superClasst, valueT);
                    field.set(instance, superClasst);
                    break;
                case "java.lang.Boolean":
                case "boolean":
                    boolean b = buffer.readBoolean();
                    field.set(instance, b);
                    break;
                case "java.lang.Character":
                case "char":
                    char charSequence = buffer.readChar();
                    field.set(instance, charSequence);
                    break;
                case "java.lang.Byte":
                case "byte":
                    byte b1 = buffer.readByte();
                    field.set(instance, b1);
                    break;
                case "java.lang.Short":
                case "short":
                    short readShort = buffer.readShort();
                    field.set(instance, readShort);
                    break;
                case "java.lang.Integer":
                case "int":
                    int readInt = buffer.readInt();
                    field.set(instance, readInt);
                    break;
                case "java.lang.Long":
                case "long":
                    long l = buffer.readLong();
                    field.set(instance, l);
                    break;
                case "java.lang.Float":
                case "float":
                    float readFloat = buffer.readFloat();
                    field.set(instance, readFloat);
                    break;
                case "java.lang.Double":
                case "double":
                    double readDouble = buffer.readDouble();
                    field.set(instance, readDouble);
                    break;
                case "java.util.Map":
                    Map<Byte, Byte> map = new HashMap<>();
                    while (true) {
                        try {
                            byte aByte = buffer.readByte();
                            byte aByte1 = buffer.readByte();
                            map.put(aByte, aByte1);
                        } catch (Exception e) {
                            field.set(instance, map);
                            break;
                        }
                    }
                    break;
                case "java.util.List":
                    List<Long> list = new ArrayList<>();
                    while (true) {
                        try {
                            long param = buffer.readLong();
                            list.add(param);
                        } catch (Exception e) {
                            field.set(instance, list);
                            break;
                        }
                    }
                    break;
                default:
                    Object o = field.getType().newInstance();
                    for (Field fieldSub : field.getType().getDeclaredFields()) {
                        fillData(fieldSub, o, buffer);
                    }
                    field.set(instance, o);
                    break;
            }
        } catch (Exception e) {
            throw new RuntimeException(typeName + "读取失败，field:" + field.getName(), e);
        }
    }

    /**
     * 对象转ByteBuf
     *
     * @param o   要转换的对象
     * @param <T> 类型
     * @return 转换结果
     */
    public static <T> byte[] ObjectToByte(T o) {
        Class aClass = o.getClass();
        ArrayList<Field> fieldsValues = parseFieldValues.get(aClass.getSimpleName());
        if (fieldsValues == null) {
            fieldsValues = new ArrayList<>();
            getFields(aClass, fieldsValues);
            parseFieldValues.put(aClass.getSimpleName(), fieldsValues);
        }
        ByteBuf byteBuf = Unpooled.buffer();
        for (Field field : fieldsValues) {
            write2ByteBuf(field, o, byteBuf);
        }
        byte[] bytes = new byte[byteBuf.readableBytes()];
        byteBuf.readBytes(bytes);
        return bytes;
    }

    /**
     * 为ByteBuf赋值
     *
     * @param field    属性
     * @param instance 对象
     * @param buffer   buffer
     */
    private static void write2ByteBuf(Field field, Object instance, ByteBuf buffer) {
        field.setAccessible(true);

        String typeName = field.getType().getName();

        Object value = null;
        try {
            value = field.get(instance);
        } catch (IllegalAccessException e) {
            new RuntimeException("反射获取值失败，filed:" + field.getName(), e);
        }
        if (value == null) {
            return;
        }

        switch (typeName) {
            case "com.bjkcst.baselib.protocolparse.bean.DefByte2Int":
//                System.out.println("获取到的数值==="+value.Int());
                int byteInt = ((DefByte2Int) value).Int;
                byte[] bytes4 = DataProcessUtils.intToByte(byteInt);
                byte[] bytesa = new byte[]{bytes4[0]};
                buffer.writeBytes(new byte[]{bytes4[0]});
                break;
            case "com.bjkcst.baselib.protocolparse.bean.DefaultBit":
                byte aByte = ((DefaultBit) value).getByte();
                buffer.writeByte(aByte);
                break;
            case "com.bjkcst.baselib.protocolparse.bean.DefTByte2Int":
//                System.out.println("获取到的数值==="+value.Int());
                int anInt = ((DefTByte2Int) value).Int;
                byte[] bytes = DataProcessUtils.intToByte2(anInt);
                buffer.writeBytes(bytes);
                break;
            case "com.bjkcst.baselib.protocolparse.bean.ByteList":
                ByteList listValue = (ByteList) value;
                ArrayList<byte[]> byteList = listValue.bytes;
                for (byte[] bytes1 : byteList) {
                    buffer.writeBytes(bytes1);
                }
                break;
            case "java.lang.Boolean":
            case "boolean":
                buffer.writeBoolean((Boolean) value);
                break;
//            case "java.lang.Character":
//            case "char":
//                buffer.writeCharSequence((CharSequence) value, Charset.forName("UTF-8"));
//                break;
            case "java.lang.Byte":
            case "byte":
                buffer.writeByte((byte) value);
                break;
            case "java.lang.Short":
            case "short":
                buffer.writeShort((short) value);
                break;
            case "java.lang.Integer":
            case "int":
                buffer.writeInt((int) value);
                break;
            case "java.lang.Long":
            case "long":
                buffer.writeLong((long) value);
                break;
            case "java.lang.Float":
            case "float":
                buffer.writeFloat((float) value);
                break;
            case "java.lang.Double":
            case "double":
                buffer.writeDouble((double) value);
                break;
//            case "java.lang.String":
//                buffer.writeCharSequence((CharSequence) value, Charset.forName("UTF-8"));
//                break;
//            case "java.time.LocalDateTime":
//                String s = ((LocalDateTime) value).toString();
//                buffer.writeCharSequence((CharSequence) s, Charset.forName("UTF-8"));
//                break;
            case "java.util.Map":
                try {
                    Map<Byte, Byte> map = (Map<Byte, Byte>) value;
                    for (byte key : map.keySet()) {
                        buffer.writeByte(key);
                        buffer.writeByte(map.get(key));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case "java.util.List":
                try {
                    List<Long> list = (List<Long>) value;
                    for (long param : list) {
                        buffer.writeLong(param);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            default:
                for (Field fieldSub : field.getType().getDeclaredFields()) {
                    write2ByteBuf(fieldSub, value, buffer);
                }
                break;
        }
    }
}
